package com;

import com.google.openrtb.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by uu on 2017/2/9.
 */
public class Main {
    public static void main(String[] args) {
        //OutputStreamWriter out = null;
        OutputStream out = null;
        BufferedReader in = null;
        InputStream is = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL("http://localhost:8084/protobuf/protobuf_adx");
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            conn.setRequestProperty("headerdata", "ceshiyongde");
            conn.setRequestProperty("Content-Type", "application/x-protobuf; charset=UTF-8");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            //out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out = conn.getOutputStream();
            Test.Test1 test1 = Test.Test1.newBuilder().setTest1("你好世界").build();
            byte[] messageBody = test1.toByteArray();


            out.write(messageBody);
            out.flush();
            //in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8"));


            is = conn.getInputStream();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] in2b = swapStream.toByteArray();
            Test.Test1 test2 = Test.Test1.parseFrom(in2b);
            System.out.println(test2.getTest1());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
